<template>
  <div>
    <!-- 定义一个输入框，不可编辑，focus时触发事件,打开一个dialog -->
    <a-input readOnly :value="value" @click="handleFocus" :placeholder="$t('columns.placeholder')"></a-input>
    <!-- 定义一个dialog -->
    <a-modal :title="$t('title')" width="69.9%" v-model="visible" @ok="handleOk" @cancel="handleCancel">
      <div class="map-tools">
        <a-radio-group v-model="mode" button-style="solid">
          <a-radio-button value="DRAW">
            绘画模式
          </a-radio-button>
          <a-radio-button value="INTERACT">
            编辑模式
          </a-radio-button>
        </a-radio-group>

        <div style="margin-left: 20px;">
          <a-button v-if="mode== 'INTERACT'" type="danger" @click="handleRemove">
            <a-icon type="delete" />
          </a-button>
        </div>
      </div>
     
      <div id="edit_fence_map" style="width: 100%; height: 520px;"></div>
    </a-modal>
  </div>
</template>
<i18n>
{
  "zh-CN": {
    "title": "编辑电子围栏",
    "columns": {
      "placeholder": "请输入围栏区域"
    }
  },
  "en-US": {
    "title": "Edit Electronic Fence",
    "columns": {
      "placeholder": "Please enter the fence area"
    }

  },
  "fr-FR": {
    "title": "Modifier la clôture électronique",
    "columns": {
      "placeholder": "Veuillez entrer la zone de la clôture"
    }
  }
}
</i18n>
<script>
import _ from 'lodash';
function isScriptAlreadyLoaded(srcCheck) {
    var scripts = document.getElementsByTagName('script');
    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src.includes(srcCheck)) {
            return true; // 如果找到匹配的src，返回true
        }
    }
    return false; // 如果没有找到匹配的src，返回false
}

export default {
  name: "EditFence",
  data() {
    return {
      visible: false,
      title: "圆形",
      map: null,
      fenceObj: null,
      editor: null,
      mode: 'DRAW'
    };
  },
  props: {
    area: {
      type: [Object,Array],
      default: ()=> ({}),
    },
    shapeType: {
      type: String,
      default: "circle",
    },
    center: {
      type: Object,
      default: ()=> {},
    },
  },
  watch:{
    mode:{
      handler(val){
        if(val == "DRAW"){
          this.editor.setSelectable(false);
          this.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.DRAW);
        }
        if(val == "INTERACT"){
          this.editor.setSelectable(true);
          this.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);
        }
      },
    }
  },
  computed: {
    value() {
      if (this.shapeType === 'circle' && !_.isEmpty(this.area)) {
        // 获取矩形顶点坐标
        const x = this.area.latitude.toFixed(6);
        const y = this.area.longitude.toFixed(6);
        const r = this.area.radius.toFixed(6);
        return `(${x},${y},${r})`;
      }
      if (this.shapeType === 'polygon' && !_.isEmpty(this.area)) {
        // 获取多边形顶点坐标
        const value = this.area.map((item) => {
          const lat = item.latitude.toFixed(6);
          const lng = item.longitude.toFixed(6);
          return `(${lat},${lng})`;
        }).join(";");
        return value;
      }
    },
  },
  methods: {
    handleRemove() {
      this.editor.delete();
      this.fenceObj = null;
      // this.$emit('update:center', "");
      // this.$emit('update:area', "");
    },
    handleFocus() {
      this.visible = true;
      this.showMap();
    },
    handleOk() {
      if(!this.fenceObj){
        this.$emit('update:fence', null);
      }else{
        if (this.shapeType === 'circle') {
          const x = this.fenceObj[0].center.lat;
          const y = this.fenceObj[0].center.lng;
          const r = this.fenceObj[0].radius;
          let circle = {
            lat: x,
            lng: y,
            radius: r
          }
          this.$emit('update:fence', circle);
        }
        if (this.shapeType === 'polygon') {
          //获取多边形顶点坐标
          const x = this.fenceObj.paths[0].lat;
          const y = this.fenceObj.paths[0].lng;
          const path = this.fenceObj.paths;
          const polygon = {
            lat: x,
            lng: y,
            paths: path
          }
          this.$emit('update:fence', polygon);
        }
      }
      this.visible = false;
    },
    handleCancel() {
      this.visible = false;
    },
    async showMap(){
      await this.loadScript(); // 使用 await 等待脚本加载完成
      if(!this.map){
        let point;
        if(_.isEmpty(this.center)){
          point = await this.getPoint();
        }else{
          point = this.center;
        }
        this.$nextTick(() => {
          this.initMap(point);
        })
      }else{
        this.initEditor()
      }
    },
    async loadScript() {
      const KEY = window._CONFIG['qqMapKey'];
      const scriptSrc = `https://map.qq.com/api/gljs?v=1.exp&libraries=tools&key=${KEY}`;
      
      return new Promise((resolve, reject) => {
        if (isScriptAlreadyLoaded(scriptSrc)) {
          console.log('The script has already been loaded.');
          resolve(); // 如果脚本已经加载，则直接解决 Promise
        } else {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src = scriptSrc;
          script.onload = () => {
            console.log('Script loaded successfully.', scriptSrc);
            resolve(); // 脚本加载完成后解决 Promise
          };
          script.onerror = (error) => {
            console.error('Error loading script:', error);
            reject(error); // 脚本加载出错时拒绝 Promise
          };
          document.body.appendChild(script);
        }
      });
    },
    initMap(point) { 
      console.log('初始化地图-----------------:');
      const center = new TMap.LatLng(point.latitude, point.longitude);
      this.map = new TMap.Map('edit_fence_map', {
          zoom: 12, // 设置地图缩放级别
          center: center, // 设置地图中心点坐标
      });
      this.initEditor();
    },
    initEditor(){
      var polygon = new TMap.MultiPolygon({
        map: this.map,
        styles: {
          highlight: new TMap.PolygonStyle({
            color: 'rgba(255, 255, 0, 0.6)',
            showBorder: true, // 是否显示边线，默认为false
            borderColor: '#3777FF', // 边线颜色
            borderWidth: 2, // 边线宽度，单位为像素
          })
        },
      });
      var circle = new TMap.MultiCircle({
        map: this.map,
        styles: {
          highlight: new TMap.CircleStyle({
            color: 'rgba(255, 255, 0, 0.6)',
            showBorder: true, // 是否显示边线，默认为false
            borderColor: '#3777FF', // 边线颜色
            borderWidth: 2, // 边线宽度，单位为像素
          })
        },
      });
      
      if(!_.isEmpty(this.area) && this.shapeType == "circle"){
        const circleGeometries = this.initCircleGeometry();
        circle.setGeometries(circleGeometries)
      }

      if(!_.isEmpty(this.area) && this.shapeType == "polygon"){
        const polygonGeometries = this.initPolygonGeometry();
        polygon.setGeometries(polygonGeometries)
      }

      this.editor = new TMap.tools.GeometryEditor({
        map: this.map, // 编辑器绑定的地图对象
        overlayList: [
          {
            overlay: polygon,
            selectedStyleId: 'highlight',
            id: 'polygon',
          },
          {
            overlay: circle,
            selectedStyleId: 'highlight',
            id: 'circle',
          },
        ],
        actionMode: this.mode === 'INTERACT' ? TMap.tools.constants.EDITOR_ACTION.INTERACT : TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
        activeOverlayId: this.shapeType, // 激活图层
        snappable: true, // 开启吸附
        selectable: this.mode === 'INTERACT', // 开启可选中
      }); // 编辑器
      this.editor.on('delete_complete', evtResult => {
					console.log("编辑器删除完成------------:", evtResult); // 编辑器删除完成
			});
      this.editor.on('adjust_complete', geometry => {
        console.log("编辑器调整完成------------:", geometry); // 编辑器调整完成
        if (this.shapeType === 'circle') {
          this.fenceObj = geometry;
          // 获取矩形顶点坐标
          // const x = geometry.center.lat.toFixed(6);
          // const y = geometry.center.lng.toFixed(6);
          // const r = geometry.radius.toFixed(6);
          // this.$emit('update:center', `(${x},${y})`);
          // this.$emit('update:area', `(${x},${y},${r})`);
        }
        if (this.shapeType === 'polygon') {
          this.fenceObj = geometry;
          // 获取多边形顶点坐标
          // const x = geometry.paths[0].lat.toFixed(6);
          // const y = geometry.paths[0].lng.toFixed(6);
          // const  center = `(${x},${y})`;
          // const path = geometry.paths.map((item) => {
          //   const lat = item.lat.toFixed(6);
          //   const lng = item.lng.toFixed(6);
          //   return `(${lat},${lng})`;
          // }).join(";");
          // this.$emit('update:center', center);
          // this.$emit('update:area', path);
        }
			});
      this.editor.on('draw_complete', (geometry) => {
        var id = geometry.id;
        if (this.editor.getActiveOverlay().id === 'circle') {
          this.fenceObj = circle.geometries.filter((item)=> item.id === id);
          // 获取矩形顶点坐标
          // var geo = circle.geometries.filter((item)=> item.id === id);
          // const x = geo[0].center.lat.toFixed(6);
          // const y = geo[0].center.lng.toFixed(6);
          // const r = geo[0].radius.toFixed(6);
          // this.$emit('update:center', `(${x},${y})`);
          // this.$emit('update:area', `(${x},${y},${r})`);
        }
        if (this.editor.getActiveOverlay().id === 'polygon') {
          this.fenceObj = geometry;
          // 获取多边形顶点坐标
          // var geo = polygon.geometries.filter((item)=> {
          //   return item.id === id;
          // });
          // const x = geo[0].paths[0].lat.toFixed(6);
          // const y = geo[0].paths[0].lng.toFixed(6);
          // const  center = `(${x},${y})`;
          // const path = geo[0].paths.map((item) => {
          //   const lat = item.lat.toFixed(6);
          //   const lng = item.lng.toFixed(6);
          //   return `(${lat},${lng})`;
          // }).join(";");
          // this.$emit('update:center', center);
          // this.$emit('update:area', path);
        }
      });
    },
    //定义一个方法，通过腾讯地图给我一个本地的经纬度单做地图中心点坐标
    getPoint() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject("Geolocation is not supported by this browser.");
        }
        navigator.geolocation.getCurrentPosition((position)=> {
          const point = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          };
          resolve(point);
        }, (error)=> {
          reject(error);
        });
      });
    },
    initCircleGeometry(){
      let geo = {};
      if(!_.isEmpty(this.area)){
        const obj = this.area;
        geo = {
          center: new TMap.LatLng(obj.latitude, obj.longitude), // 圆心坐标
          radius: obj.radius, // 半径，单位为米
          styleId:new TMap.CircleStyle({
            color: 'rgba(55,119,255,0.16)', // 填充色
            showBorder: true, // 是否显示边线，默认为false
            borderColor: '#3777FF', // 边线颜色
            borderWidth: 2, // 边线宽度，单位为像素
          })
        }
      }
      return [geo];
    },
    initPolygonGeometry(){
      let geo = {};
      if(!_.isEmpty(this.area)){
        const objarr = this.area;
        const paths = [];
        objarr.forEach((item)=>{
          const lat = item.latitude;
          const lng = item.longitude;
          paths.push(new TMap.LatLng(lat,lng));
        })
        geo = {
          paths: paths,
          styleId:new TMap.PolygonStyle({
            color: 'rgba(55,119,255,0.16)', // 填充色
            showBorder: true, // 是否显示边线，默认为false
            borderColor: '#3777FF', // 边线颜色
            borderWidth: 2, // 边线宽度，单位为像素
          })
        }
      }
      return [geo];
    }
  },
}
</script>

<style scoped>
.map-tools{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>